let centerNameArea = document.getElementById('name');
let namesArr = document.querySelectorAll('.player_box .box_left');
let tables = document.getElementsByTagName('table');
let hands = document.querySelectorAll('.hand');
let deskTitle = document.querySelector('.desk .title');
let restCards = document.querySelector('.rest_card');
let deadCards = document.querySelector('.dead_card');
let cardArea = document.querySelector('.card_area');
let onlineContainer = document.querySelector('.onlineContainer');
let onlinePlayerArea = document.querySelector('.onlinePlayerList');
let startBtn = document.getElementById('startBtn');
let createRoomBtn = document.getElementById('createBtn');
let joinRoomBtn = document.getElementById('joinBtn');
let roomNumInp = document.getElementById('roomNumInp');
let confirmBtn = document.querySelector('.confirmBtn');
let loginContainer = document.getElementById('loginContainer');
let showBtn = document.getElementById('showOnlinePlayerAreaBtn');
let sendBtn = document.getElementById('sendBtn');
let sendMsgInp = document.getElementById('sendMsgInp');
// 音效
let shua = document.querySelector('.shua');
// 保存在线玩家
let onlinePlayers = [];
// 保存当前游戏必要的数据 restCard deadCards[] activePlayerDeskIndex 
let gameInfo = {};
// 记录输入消息的时间
let sendMsgTimer = null;
// 将要发送的目标私聊玩家sid
let sendSid = null;
// 记录玩家匹配等待的时间
let waitTimer = null;
let waitCount = 0;
// 顶部标题作为消息窗口
let prevMsgOnTitle = [];
let msgTimer = null;

function hideScreen(classname) {
	document.querySelector(`.${classname}`).style.display = "none";
}

function showScreen(classname) {
	document.querySelector(`.${classname}`).style.display = "block";
}

function showMsgOnTitle(msg) {
	console.log(msg);
	if (typeof msg == 'object') {
		prevMsgOnTitle.push(JSON.stringify(msg));
	} else if (typeof msg == 'string') {
		prevMsgOnTitle.push(msg);
	}
	if (!msgTimer) {
		msgTimer = setInterval(() => {
			if (prevMsgOnTitle.length > 0) {
				deskTitle.innerText = prevMsgOnTitle[0];
				prevMsgOnTitle.shift();
			} else {
				clearInterval(msgTimer);
				msgTimer = null;
			}
		}, 1300)
	}
}
// 初始化抽牌堆
function initRestCardRender() {
	if (gameInfo.restCard > -1) {
		restCards.childNodes[0].nodeValue = `抽牌堆剩余${gameInfo.restCard}`;
	}
}
// 初始化弃牌堆
function initDeadCardRender() {
	if (gameInfo.deadCards.length == 0) {
		deadCards.innerHTML = `弃牌堆已清空`
	} else if (gameInfo.deadCards.length > -1) {
		deadCards.childNodes[0].nodeValue = `弃牌堆剩余${gameInfo.deadCards.length}`;
	}
}
// 往弃牌堆加入一张牌
function addCardToDeadCardHeap(card) {
	deadCards.appendChild(createCard(card));
}
// 弃牌堆移除最顶上的一张牌
function removeCardFromDeadCardHeap() {
	if (deadCards.childElementCount > 0) {
		if (deadCards.lastElementChild != null) {
			// 从弃牌堆打出牌时，将该牌放到中央牌区
			cardArea.appendChild(deadCards.lastElementChild);
			deadCards.lastElementChild.remove();
		} else {
			console.log("弃牌堆没有牌，却执行了移除函数");
		}
		// 弃牌堆剩余的牌怎么不显示了
	}
}
// 这张牌打出到中央区域
function addCardToArea(card) {
	cardArea.appendChild(createCard(card));
}
// 可选--从中央区域移除最近的一张牌--主要是交易时打出的牌要不要留在场上
function removeLastCardFromArea() {
	// cardArea.lastElementChild.remove();
}
// 玩家的手牌增加
function addCardToPlayerHand(deskIndex, card) {
	deskIndex = getPlayerAreaIndex(deskIndex);
	hands[deskIndex].appendChild(createCard(card));
}
// 从手牌移除该牌 传了 card 说明是手牌或明牌被移走 没传 card 说明移走了卡背
function removeCardFromPlayerHand(deskIndex, card) {
	deskIndex = getPlayerAreaIndex(deskIndex);
	if (!card) {
		hands[deskIndex].firstElementChild.remove();
	} else {
		for (let i = 0; i < hands[deskIndex].children.length; i++) {
			const element = hands[deskIndex].children[i];
			if (element.dataset.index == card) {
				element.remove();
				break;
			}
		}
	}
}
// 初始化所有玩家的手牌
function renderHandCard() {
	if (typeof user.handCard == 'object') {
		// 渲染自己的手牌
		user.handCard.forEach(i => {
			hands[2].appendChild(createCard(i));
		});
		// 渲染其他玩家的牌背
		for (let i = 31; i < 36; i++) {
			hands[0].appendChild(createCard(i));
			hands[1].appendChild(createCard(i));
		}
	}
}
// 默认创建一张手牌中的暗牌，但是当第一个参数大于30时，创建的是卡背
function createCard(i) {
	let card = document.createElement('div');
	card.style.width = "80px";
	card.style.height = "80px";
	if (i <= 30) {
		card.style.background = "url('./puke.png')";
		card.style.backgroundPosition = `-${(i % 10 == 0 ? 9 : ((i % 10) - 1)) * 80}px -${~~(i / 10 - (i % 10 == 0 ? 1 : 0)) * 80}px`;
		card.dataset.index = i;
	} else {
		card.classList.add('card_bg');
	}
	card.classList.add('handCard');
	return card;
}
// 保存并渲染当前玩家基本信息
function gameRenderInit() {
	if (loginState == 'loginOk') {
		let rooms = document.querySelector(".roomScreen ul")
		// 改变有人落座的房间的座位背景
		for (let i = 0; i < room.seat.length; i++) {
			for (let j = 0; j < room.seat[i]; j++){
				rooms.children[i].children[j].classList.add('hadSeat');
			}
		}
		showScreen('roomScreen')
	}
	return;
	namesArr[2].innerText = loginName;
	document.body.hidden = false;
	if (loginState == 'normal') {
		// 如果是正常的首次登录，渲染当前玩家的名字
		centerNameArea.innerText = loginName;
		startBtn.disabled = false;
		createRoomBtn.disabled = false;
		joinRoomBtn.disabled = false;
		roomNumInp.disabled = false;
	} else if (loginState == 'reconnect') {
		// 重新连接，请求服务器返回这一局当前的游戏数据，再进行渲染
		showMsgOnTitle(`${loginName}重新进入游戏`);
		// 走一遍发牌等开局渲染流程
		renderPlayersName();
		removeStartBtnWaiting();
		// 算分,不能用原先的初始手牌算法了,因为手牌变化了

		// 看牌
		renderHandCard();
		// 渲染抽牌堆和弃牌堆
		initRestCardRender();
		initDeadCardRender();
		// 默认当前是打出模式
		user.justConsume = true;
		renderSeeOfflineData();
		// 开启一次普通回合循环（允许活动玩家做行动，非活动玩家不动）
		gameLoop();
		// 掉线重连功能，等待测试
	}
}
// 渲染游戏过程中的信息
// 掉线重连时需要渲染的离线补充信息，明牌、已知隐藏分等
function renderSeeOfflineData() {
	console.log(seeOfflineData);
	// 渲染上家的隐藏分
	let hiddenScore = seeOfflineData.hiddenScore;
	for (let i = 0; i < hiddenScore.length; i++) {
		tables[0].children[0].children[2].children[1 + i].firstElementChild.value = hiddenScore[i];
		tables[0].children[0].children[2].children[1 + i].firstElementChild.disabled = "true";
	}
	// 渲染已知的隐藏分
	for (let i = 0; i < seeOfflineData.seeHiddenScore.length; i++) {
		if (seeOfflineData.seeHiddenScore[i] > 0) {
			renderPlayerHiddenScore(i, seeOfflineData.seeHiddenScore[i]);
		}
	}
	// 渲染已知的明牌
	for (let j = 0; j < seeOfflineData.seeCards.length; j++) {
		const cards = seeOfflineData.seeCards[j];
		if (cards && cards.length > 0) {
			// 先处理下家，再处理上家
			let deskIndex = (user.deskIndex + 1 + j) % 3
			for (let i = 0; i < cards.length; i++) {
				// 移除一张牌背
				removeCardFromPlayerHand(deskIndex);
				// 添加一张明牌
				addCardToPlayerHand(deskIndex, cards[i])
			}
		}
	}
	// 用完清零
	seeOfflineData = {};
}
// 渲染玩家的名称
function renderPlayersName() {
	console.log(user.players);
	if (user.players.length == 2) {
		if (user.deskIndex == 0) {
			namesArr[1].innerText = user.players[1].name;
		} else if (user.deskIndex == 1) {
			namesArr[0].innerText = user.players[0].name;
		}
	} else if (user.players.length == 3) {
		if (user.deskIndex == 2) {
			namesArr[0].innerText = user.players[1].name;
			namesArr[1].innerText = user.players[0].name;
		} else {
			namesArr[user.deskIndex].innerText = user.players[2].name;
		}
	} else if (user.players.length == 1) {
		namesArr[0].innerText = "空座位";
		namesArr[1].innerText = "空座位";
	}
}
// 渲染用户在匹配过程中的等待时间
function renderStartBtnWaiting() {
	if (!waitTimer) {
		waitTimer = setInterval(() => {
			startBtn.innerText = `已等待${waitCount++}秒`;
			if (waitCount == 60) {
				// 可选做,通知服务器,已经等了1分钟了
			}
		}, 1000);
	}
	disableAllBtn();
}
function disableAllBtn() {
	startBtn.disabled = true;
	createRoomBtn.disabled = true;
	joinRoomBtn.disabled = true;
	roomNumInp.disabled = true;
}
function removeStartBtnWaiting() {
	// 出现先手玩家，说明游戏开始了
	clearInterval(waitTimer);
	waitCount = 0;
	// 移除“正在匹配”的登录及通知窗口
	loginContainer.style.display = "none";
}
function renderConfirmBtnText() {
	if (user.justConsume) {
		confirmBtn.innerText = "直接出牌";
		confirmBtn.classList.remove('onTradeBtn');
		user.curChooseCard = -1;
	} else {
		confirmBtn.innerText = "拼点";
		confirmBtn.classList.add('onTradeBtn');
		// 当前玩家有手牌时，遍历其他人的手牌，允许当前玩家点击明牌，再点击自己手牌，进行强制交易操作
		if (user.handCard.length > 0) {
			let tmp = hands[0].querySelectorAll(':not(.card_bg).handCard');
			for (let i = 0; i < tmp.length; i++) {
				const element = tmp[i];
				if (element.dataset.index > 0) {
					element.addEventListener('click', setCurChooseCard);
				}
			}
			tmp = hands[1].querySelectorAll(':not(.card_bg).handCard');
			for (let i = 0; i < tmp.length; i++) {
				const element = tmp[i];
				if (element.dataset.index > 0) {
					element.addEventListener('click', setCurChooseCard);
				}
			}
		}
	}
}
function setCurChooseCard(e) {
	console.log(e.target.dataset.index);
	user.curChooseCard = parseInt(e.target.dataset.index);
	// 只能选择一次目标牌，选完移除事件监听器
	let tmp = hands[0].querySelectorAll(':not(.card_bg).handCard');
	for (let i = 0; i < tmp.length; i++) {
		const element = tmp[i];
		if (element.dataset.index > 0) {
			element.removeEventListener('click', setCurChooseCard);
		}
	}
	tmp = hands[1].querySelectorAll(':not(.card_bg).handCard');
	for (let i = 0; i < tmp.length; i++) {
		const element = tmp[i];
		if (element.dataset.index > 0) {
			element.removeEventListener('click', setCurChooseCard);
		}
	}
}
function getPlayerAreaIndex(deskIndex) {
	let tableIndex = -1;
	if (deskIndex > -1) {
		if (user.deskIndex == deskIndex) {
			tableIndex = 2;
		} else if ((user.deskIndex == 0 && deskIndex == 2)
			|| (user.deskIndex == 1 && deskIndex == 0)
			|| (user.deskIndex == 2 && deskIndex == 1)) {
			tableIndex = 0;
		} else {
			tableIndex = 1;
		}
	}
	return tableIndex;
}
// 渲染该玩家的三项表面分数
function renderScore(deskIndex, s0, s1, s2) {
	let tableIndex;
	if (deskIndex > -1) {
		tableIndex = getPlayerAreaIndex(deskIndex);
		tables[tableIndex].children[0].children[1].children[1].innerText = s0;
		tables[tableIndex].children[0].children[1].children[2].innerText = s1;
		tables[tableIndex].children[0].children[1].children[3].innerText = s2;
	}
}
function renderPlayerHiddenScore(type, score) {
	tables[2].children[0].children[2].children[type + 1].firstElementChild.value = score;
}
// 隐藏分渲染
function renderHiddenScore(cards) {
	let scoreArea = [
		tables[0].children[0].children[2].children[1].firstElementChild,
		tables[0].children[0].children[2].children[2].firstElementChild,
		tables[0].children[0].children[2].children[3].firstElementChild
	];
	if (cards[1] < 10) {
		scoreArea[0].value = Math.min(cards[0], cards[1]);
		if (cards[3] < 20) {
			scoreArea[1].value = Math.min(cards[2] - 10, cards[3] - 10);
			scoreArea[2].value = (cards[4] - 20) * 2;
		} else {
			scoreArea[1].value = (cards[2] - 10) * 2;
			scoreArea[2].value = Math.min(cards[3] - 20, cards[4] - 20);
		}
	} else {
		scoreArea[0].value = cards[0] * 2;
		scoreArea[1].value = Math.min(cards[1] - 10, cards[2] - 10);
		scoreArea[2].value = Math.min(cards[3] - 20, cards[4] - 20);
	}
	scoreArea[1].disabled = "true";
	scoreArea[2].disabled = "true";
	scoreArea[0].disabled = "true";
}
// 更新在线玩家列表
function updateOnlinePlayers() {
	onlinePlayerArea.innerHTML = '';
	// 加入
	for (let i = 0; i < onlinePlayers.length; i++) {
		let li = document.createElement('li');
		li.innerText = onlinePlayers[i].name;
		li.dataset.sid = onlinePlayers[i].sid;
		onlinePlayerArea.appendChild(li);
	}
}
// 切换在线玩家列表区域的显示隐藏
function showOnlinePlayerArea() {
	if (onlineContainer.style.right != '0px') {
		showBtn.style.right = '150px';
		onlineContainer.style.right = '0px';
	} else {
		showBtn.style.right = '0px';
		onlineContainer.style.right = '-150px';
	}
}
// 选中玩家时，给他加一个类名 selectPlayer 
onlinePlayerArea.addEventListener('click', (e) => {
	console.log(e);
	// 清除所有
	for (let i = 0; i < onlinePlayerArea.childElementCount; i++) {
		if (onlinePlayerArea.children[i].classList.contains('selectPlayer')) {
			onlinePlayerArea.children[i].classList.remove('selectPlayer');
		}
	}
	// 选中目标
	e.target.classList.add('selectPlayer');
	sendSid = e.target.dataset.sid;
});
// 监听发送消息内容的输入
sendMsgInp.addEventListener('input', () => {
	if (!sendMsgTimer) {
		sendMsgTimer = setTimeout(() => {
			clearTimeout(sendMsgTimer);
			if (sendSid && sendMsgInp.value) {
				sendBtn.disabled = false;
			}
			sendMsgTimer = null;
		}, 1200);
	}
});
function clearMsgInp() {
	// 清空消息发送内容输入框
	sendMsgInp.value = '';
	sendBtn.disabled = true;
}
// 允许打出明牌
function canPlayBanCard(card) {
	let cards = hands[2].querySelectorAll('.banCard');
	for (let i = 0; i < cards.length; i++) {
		if (cards[i].dataset.index == card) {
			cards[i].classList.remove('banCard');
		}
	}
}
function banCard(card) {
	for (let i = 0; i < hands[2].children.length; i++) {
		const e = hands[2].children[i];
		if (e.dataset.index == card) {
			e.classList.add('banCard');
		}
	}
}
function renderGameOverBtn() {
	// 渲染一个再来一局的按钮
	loginContainer.style.display = 'block';
	loginContainer.innerHTML = '';
	let btn = document.createElement('button');
	btn.innerText = '再来一局';
	btn.addEventListener('click', gameAgain);
	loginContainer.appendChild(btn);
}

function renderActivePlayerStyle() {
	let index = getPlayerAreaIndex(gameInfo.activePlayerDeskIndex)
	for (let i = 0; i < namesArr.length; i++) {
		if (namesArr[i].classList.contains('activePlayer')) {
			namesArr[i].classList.remove('activePlayer');
		}
	}
	namesArr[index].classList.add('activePlayer');
}
// 清除所有玩家的手牌区、桌面分
function clearHandCardAndScore() {
	for (let i = 0; i < hands.length; i++) {
		const hand = hands[i];
		hand.innerHTML = '';
		// 清除桌面分
		renderScore(i, 0, 0, 0);
	}
}
// 清除中央牌区、抽牌堆、弃牌堆
function clearCardArea() {
	cardArea.innerHTML = ''
	cardArea.appendChild(restCards)
	cardArea.appendChild(deadCards)
}